
# $Id: Point.pm 140 2013-04-11 02:35:23Z chengxin.cai $

use strict;

package Rectangle;
use base 'Shape';

use Switch;
use Carp;
use PerlUtil qw( gen_getter gen_setter );

sub import {
    my $package = shift;
    $package =~ s/.*:://;

    ##export the constructor
    no strict 'refs';
    my ($caller) = caller;
    *{ $caller . '::' . $package } = \&{$package};

    ##install getters and setters
    gen_getter( __PACKAGE__, 'p1' );
    gen_getter( __PACKAGE__, 'p2' );

    gen_setter( __PACKAGE__, 'set_p1' );
    gen_setter( __PACKAGE__, 'set_p2' );

}

sub Rectangle {
    my ( $p1, $p2 ) = @_;

    bless sub {
        my $op = shift;
        switch ($op) {
            case 'p1'   { return $p1; }
            case 'p2'   { return $p2; }
            else        { croak 'Invalid operation ' . $op; }
        }
    }, __PACKAGE__;
}

use overload q{""} =>sub {
        my $self = shift;

        my $p1 = $self->p1();
        my $p2 = $self->p2();

        sprintf "#<%s p1: (%.1f, %.1f), p2: (%.1f, %.1f)>",
            ref $self, $p1->x(), $p1->y(), $p2->x(), $p2->y();
};

sub area {
    my $self = shift;

    my $p1 = $self->p1();
    my $p2 = $self->p2();

    ($p1->x() - $p2->x()) * ($p1->y() - $p2->y());
}

sub draw {
    my $self = shift;

    print "Draw a rectangle\n";
}

1;

